<template>
  <div class="doctor-dashboard">
    <el-container>
      <el-header class="dashboard-header">
        <div class="header-content">
          <h2>医生工作台</h2>
          <div class="user-info">
            <el-dropdown @command="handleCommand">
              <span class="user-dropdown">
                <el-avatar 
                  :src="doctorInfo.avatar || '/default-avatar.png'" 
                  :size="40"
                />
                <span class="username">{{ doctorInfo.realName || doctorInfo.username }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                  <el-dropdown-item command="avatar">更换头像</el-dropdown-item>
                  <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-main class="dashboard-main">
        <el-row :gutter="20">
          <!-- 个人信息卡片 -->
          <el-col :span="8">
            <el-card class="info-card">
              <template #header>
                <div class="card-header">
                  <span>个人信息</span>
                  <el-button type="primary" size="small" @click="editProfile">编辑</el-button>
                </div>
              </template>
              <div class="profile-info">
                <div class="avatar-section">
                  <el-avatar 
                    :src="doctorInfo.avatar || '/default-avatar.png'" 
                    :size="80"
                  />
                  <el-button 
                    type="primary" 
                    size="small" 
                    class="upload-btn"
                    @click="showAvatarUpload = true"
                  >
                    更换头像
                  </el-button>
                </div>
                <div class="info-list">
                  <div class="info-item">
                    <span class="label">用户名：</span>
                    <span class="value">{{ doctorInfo.username }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{ doctorInfo.realName || '未设置' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">邮箱：</span>
                    <span class="value">{{ doctorInfo.email }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">电话：</span>
                    <span class="value">{{ doctorInfo.phone || '未设置' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">性别：</span>
                    <span class="value">{{ getGenderText(doctorInfo.gender) }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">执业范围：</span>
                    <span class="value">{{ doctorInfo.practiceScope || '未设置' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">等级：</span>
                    <span class="value">Lv.{{ doctorInfo.level }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">积分：</span>
                    <span class="value">{{ doctorInfo.points }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 统计信息卡片 -->
          <el-col :span="8">
            <el-card class="stats-card">
              <template #header>
                <div class="card-header">
                  <span>统计信息</span>
                </div>
              </template>
              <div class="stats-content">
                <div class="stat-item">
                  <div class="stat-number">0</div>
                  <div class="stat-label">今日问诊</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">0</div>
                  <div class="stat-label">本月问诊</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">0</div>
                  <div class="stat-label">总问诊数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ doctorInfo.points }}</div>
                  <div class="stat-label">当前积分</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 快捷操作卡片 -->
          <el-col :span="8">
            <el-card class="action-card">
              <template #header>
                <div class="card-header">
                  <span>快捷操作</span>
                </div>
              </template>
              <div class="action-content">
                <el-button type="primary" size="large" class="action-btn">
                  <el-icon><ChatDotRound /></el-icon>
                  开始问诊
                </el-button>
                <el-button type="success" size="large" class="action-btn">
                  <el-icon><Document /></el-icon>
                  查看病历
                </el-button>
                <el-button type="warning" size="large" class="action-btn">
                  <el-icon><Calendar /></el-icon>
                  预约管理
                </el-button>
                <el-button type="info" size="large" class="action-btn">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    
    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="更换头像"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="avatar-upload">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="customUpload"
          accept=".jpg,.jpeg,.png,.gif,.bmp"
        >
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 jpg, jpeg, png, gif, bmp 格式</p>
          <p>文件大小不超过 5MB</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAvatarUpload = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAvatarUpload"
            :loading="uploading"
          >
            确认上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowDown, 
  Plus, 
  ChatDotRound, 
  Document, 
  Calendar, 
  Setting 
} from '@element-plus/icons-vue'
import { getDoctorInfo, uploadAvatar } from '../api/doctor'

const router = useRouter()
const showAvatarUpload = ref(false)
const uploading = ref(false)
const avatarUrl = ref('')
const uploadRef = ref()

const doctorInfo = reactive({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  gender: null,
  birthDate: '',
  address: '',
  practiceScope: '',
  points: 0,
  level: 3,
  avatar: '',
  createTime: ''
})

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    // 优先从本地存储获取医生信息
    const localDoctorInfo = localStorage.getItem('doctorInfo')
    if (localDoctorInfo) {
      try {
        const parsedInfo = JSON.parse(localDoctorInfo)
        Object.assign(doctorInfo, parsedInfo)
      } catch (e) {
        console.warn('本地存储的医生信息格式错误，重新获取')
      }
    }
    
    // 从后端获取最新的医生信息
    const response = await getDoctorInfo()
    if (response.code === 200) {
      Object.assign(doctorInfo, response.data)
      // 更新本地存储
      localStorage.setItem('doctorInfo', JSON.stringify(doctorInfo))
    } else {
      ElMessage.error(response.message || '获取信息失败')
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取信息失败，请检查网络连接')
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      editProfile()
      break
    case 'avatar':
      showAvatarUpload.value = true
      break
    case 'logout':
      logout()
      break
  }
}

// 编辑个人信息
const editProfile = () => {
  ElMessage.info('个人信息编辑功能开发中...')
}

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    localStorage.removeItem('doctorToken')
    localStorage.removeItem('doctorInfo')
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

// 获取性别文本
const getGenderText = (gender) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未设置'
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = /\.(jpg|jpeg|png|gif|bmp)$/i.test(file.name)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 阻止默认上传
}

// 自定义上传
const customUpload = (options) => {
  // 这里只是预览，实际上传在确认按钮点击时进行
  console.log('File selected:', options.file)
}

// 确认头像上传
const confirmAvatarUpload = async () => {
  if (!avatarUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  try {
    uploading.value = true
    
    // 将 base64 转换为文件
    const response = await fetch(avatarUrl.value)
    const blob = await response.blob()
    const file = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
    
    const formData = new FormData()
    formData.append('avatar', file)
    
    const uploadResponse = await uploadAvatar(formData)
    
    if (uploadResponse.code === 200) {
      ElMessage.success('头像上传成功')
      doctorInfo.avatar = uploadResponse.data.avatarUrl
      
      // 更新本地存储的医生信息
      localStorage.setItem('doctorInfo', JSON.stringify(doctorInfo))
      
      showAvatarUpload.value = false
      avatarUrl.value = ''
    } else {
      ElMessage.error(uploadResponse.message || '上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('上传失败，请检查网络连接')
  } finally {
    uploading.value = false
  }
}

// 组件挂载时获取医生信息
onMounted(() => {
  fetchDoctorInfo()
})
</script>

<style scoped>
.doctor-dashboard {
  height: 100vh;
  background-color: #f5f5f5;
}

.dashboard-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f7fa;
}

.username {
  margin: 0 8px;
  color: #303133;
  font-weight: 500;
}

.dashboard-main {
  padding: 20px;
}

.info-card,
.stats-card,
.action-card {
  height: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.upload-btn {
  margin-top: 10px;
}

.info-list {
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
}

.stats-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.action-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-btn {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar-preview {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips p {
  margin: 5px 0;
}

.dialog-footer {
  text-align: right;
}
</style> 